package com.test;

import java.io.InputStream;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.model.StageInfo;
import com.pdfviewer.PdfViewerActivity;
import com.utils.Downloader;
import com.utils.FileUtils;
import com.utils.StageInfoAdapter;

public class StageListActivity extends ListActivity {

	public static final String EXTRA_PDFFILENAME = "net.sf.andpdf.extra.PDFFILENAME";
	private final static String PATH = "pdfReport/";
	private List<StageInfo> stageInfoList = null;
	private StageInfoAdapter stageInfoAdapter;
	private Downloader downloader = new Downloader();
	private InputStream inputDataStream = null;
	private ListView listView;
	private Builder downloadAlertDialog;
	private Builder uploadAlertDialog;
	private StageInfo stageInfo = new StageInfo();
	private FileUtils fileUtils = new FileUtils();

	private final String configPath="config/ece_configuration.conf";
	private String server;
	
	private String promolist="5";


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		promolist = getIntent()
				.getStringExtra(StageTabListAvtivity.EXTRA_PROMO);

		String config=fileUtils.getFileContent(configPath);
		server=config.split("\n")[0].split("::")[1].toString();
		String user=config.split("\n")[1].split("::")[1].toString();
		
		//"http://10.4.133.20/stage/index.php/"
		this.inputDataStream = downloader.postProf("list",

				server+"/stage/rapportList",
				"login_ece", user,promolist);

		this.stageInfoList = downloader.runJSONParser(inputDataStream);
		this.getStageInfoList();
		this.stageInfoAdapter = new StageInfoAdapter(this,
				R.layout.itemrenderer, stageInfoList);
		setListAdapter(this.stageInfoAdapter);
		this.listView = getListView();
		this.downloadAlertDialog = new Builder(StageListActivity.this);
		this.uploadAlertDialog = new Builder(StageListActivity.this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				stageInfo = stageInfoList.get(position);
				final String downloadReportName = stageInfo.getFileInfo()
						+ "_RapportOriginal.pdf";
				ImageView icon=(ImageView) view.findViewById(R.id.icondownload);

				if (fileUtils.isFileExist(PATH + downloadReportName)) {
					Intent intent = new Intent(getApplicationContext(),
							PdfViewerActivity.class).putExtra(
							EXTRA_PDFFILENAME, fileUtils.getFileAbsolutePath(
									PATH, downloadReportName));
					startActivity(intent);
				} else {
					Downloader downloader = new Downloader();
					String url = server+"/rapportEvaluation/getOriginalPDF?security_key=";
					String security_value = stageInfo.getSecurity_key();
					int flag = downloader.downloadPDF(url + security_value,
							PATH, downloadReportName);
					stageInfoAdapter.btnSensitive(PATH,
							downloadReportName, icon);
					if (flag == 0) {
						Intent intent = new Intent(getApplicationContext(),
								PdfViewerActivity.class).putExtra(
								EXTRA_PDFFILENAME, fileUtils
										.getFileAbsolutePath(PATH,
												downloadReportName));
						startActivity(intent);
					}
				}
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stubs
				stageInfo = stageInfoList.get(position);
				final String downloadReportName = stageInfo.getFileInfo()
						+ "_RapportOriginal.pdf";
				final String uploadReportName = stageInfo.getFileInfo()
						+ "_RapportFinal.pdf";
				final ImageView icon=(ImageView) view.findViewById(R.id.icondownload);

				if (fileUtils.isFileExist(PATH + uploadReportName)) {
					uploadAlertDialog
							.setMessage(
									"Do you want to upload the report of "
											+ stageInfo.getStudent_fullname()
											+ " ?")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											String url = server+"/rapportEvaluation/uploadFinalPDF";
											String nameAtrribute = "RapportEvaluation[file]";
											int flag;
											flag = downloader.uploadPDF(PATH,
													uploadReportName, url,
													nameAtrribute,
													stageInfo.getSecurity_key());
											System.out.println(flag);
											stageInfoAdapter
													.uploadNotification(flag);
											// Action for 'Yes' Button
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = uploadAlertDialog.create();
					// Title for AlertDialog
					alert.setTitle("Upload");
					// Icon for AlertDialog
					alert.setIcon(R.drawable.icon);
					alert.show();

					return false;
				} else if (!fileUtils.isFileExist(PATH + downloadReportName)) {
					downloadAlertDialog
							.setMessage(
									"Do you want to download the report of "
											+ stageInfo.getStudent_fullname()
											+ " ?")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// Action for 'Yes' Button
											Downloader downloader = new Downloader();
											String url = server+"/rapportEvaluation/getOriginalPDF?security_key=";
											String security_value = stageInfo
													.getSecurity_key();
											int flag = downloader.downloadPDF(
													url + security_value, PATH,
													downloadReportName);
											System.out.println(url
													+ security_value);
											System.out.println(flag);
											stageInfoAdapter
													.downloadNotification(flag);
											stageInfoAdapter.btnSensitive(PATH,
													downloadReportName, icon);
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = downloadAlertDialog.create();
					// Title for AlertDialog
					alert.setTitle("Download");
					// Icon for AlertDialog
					alert.setIcon(R.drawable.icon);
					alert.show();
				}

				else {
					Toast msg = Toast.makeText(StageListActivity.this,
							R.string.download_exist, Toast.LENGTH_SHORT);
					msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
							msg.getYOffset() / 2);
					msg.show();

				}
				return true;
			}
		});
	}

	private void getStageInfoList() {

		for (int i = 0; i < stageInfoList.size(); i++) {
			System.out.println("StageInfo Id: " + stageInfoList.get(i).getId());
			System.out.println("Report FileName: "
					+ stageInfoList.get(i).getFile_name());
			System.out.println("Stage Code: " + stageInfoList.get(i).getCode());
			System.out.println("Report Plagiat: "
					+ stageInfoList.get(i).getPlagiat_percentage());
			System.out.println("Security Key: "
					+ stageInfoList.get(i).getSecurity_key());
			System.out.println("Report Status: "
					+ stageInfoList.get(i).getStatus());
			System.out.println("Student Name: "
					+ stageInfoList.get(i).getStudent_fullname());
			System.out.println("Student Promotion: "
					+ stageInfoList.get(i).getPromo());
			System.out.println("Student Major: "
					+ stageInfoList.get(i).getMajeure());
			System.out.println("Student Program: "
					+ stageInfoList.get(i).getProgramme());
		}

	}
}